package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 宋H
 * @Date: 2022/9/13
 * @Description: com.itheima.controller
 * @version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/user")
@Api(tags="用户信息相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 获取手机验证码
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> userCode(@RequestBody User user, HttpServletRequest request){
        log.info(user.toString());
        //首先获取手机号
        String phone = user.getPhone();
        //通过工具类生成4位随机验证码
        if(StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909","15207903859","code");
            //需要将生成的验证码保存到Session
            //request.getSession().setAttribute(phone,code);

            //将生成的验证码缓存到Redis中，并且设置有效期为3分钟
            ValueOperations vos = redisTemplate.opsForValue();
            vos.set(phone,code,3, TimeUnit.MINUTES);
            return R.success("手机验证码发送成功");
        }
        return R.success("验证码发送失败");
    }

    /**
     * 通过获取的验证码，进行用户登录
     * @param map
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<User> userLogin(@RequestBody Map map, HttpServletRequest request){
        log.info(map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //对比获取的验证码和session中的验证码是否一样
        //String sessionCode = request.getSession().getAttribute(phone).toString();
        //从Redis中获取缓存的验证码
        Object sessionCode = redisTemplate.opsForValue().get(phone);
        if(sessionCode.equals(code)&&sessionCode!=null){
            //登录成功后，检查数据库中是否有该手机号，没有注册
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User user = userService.getOne(lqw);
            if(user==null){
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            //将当前用户的id存储到session中，避免过滤器跳转
            request.getSession().setAttribute("user",user.getId());

            return R.success(user);
        }
        return R.error("短信验证失败,请重新发送");
    }

    @PostMapping("/loginout")
    public R<String> userLogOut(){

        return R.success("退出成功");
    }
}
